import { BaseToolProvider } from "./base";
import { z } from "zod";
import * as mysql from 'mysql2/promise';
import { ToolCall } from "./types";

export class MysqlToolProvider extends BaseToolProvider {
	connectionString?: string;
	constructor() {
		super();
		this.addTool({
			name: 'execute_sql',
			description: "在MySQL中执行SQL语句返回结果",
			parameters: z.object({
				sql: z.string({ description: "待执行SQL语句", required_error: '没有待执行的SQL语句' })
			})
		}, this.executeSql);
	}

	async executeSql(call: ToolCall): Promise<any> {
		if(!this.connectionString) {
			throw new Error('没有配置数据库连接信息');
		}
		const connection = await mysql.createConnection(this.connectionString);
		const parameter = JSON.parse(call.arguments);
		return await connection.query(parameter.sql);
	}
}